/*
 * FaceCat图形通讯框架
 * 著作权编号:2015SR229355+2020SR0266727
 * 上海卷卷猫信息技术有限公司
 */

#include "..\\..\\stdafx.h"
#include "..\\..\\include\\sock\\FCClientSocket.h"
#include "..\\..\\include\\sock\\FCClientSockets.h"

namespace FaceCat{
    HashMap<int, FCClientSocket*> m_clients;
    FCLock m_clientsLock;

    RecvMsg m_recvServerMsgCallBack = 0;

    WriteClientLog m_writeClientLogCallBack = 0;

    void FCClientSockets::recvServerMsg(int socketID, int localSID, const char *str, int len){
        if(m_recvServerMsgCallBack){
            m_recvServerMsgCallBack(socketID, localSID, str, len);
        }
    }

    void FCClientSockets::writeLog(int socketID, int localSID, int state, const char *log){
        if(m_writeClientLogCallBack){
            m_writeClientLogCallBack(socketID, localSID, state, log);
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////

    int FCClientSockets::close(int socketID){
        ::closesocket(socketID);
        m_clientsLock.lock();
        if(m_clients.containsKey(socketID)){
            FCClientSocket *client = m_clients.get(socketID);
            int ret = client->close(socketID);
            m_clients.remove(socketID);
            client = 0;
            m_clientsLock.unLock();
            return ret;
        }
        m_clientsLock.unLock();
        return SOCKET_ERROR;
    }

    int FCClientSockets::connect(int proxyType, const char *ip, int port, const char *proxyIp, int proxyPort, const char *proxyUserName, const char *proxyUserPwd, const char *proxyDomain, int timeout, char *token){
        FCClientSocket *client = new FCClientSocket(proxyType, ip, port, proxyIp, proxyPort, proxyUserName, proxyUserPwd, proxyDomain, timeout, token);
        ConnectStatus ret = client->connect();
        if(ret != CONNECT_SERVER_FAIL){
            int socketID = (int)client->m_hSocket;
            m_clientsLock.lock();
            m_clients.put(socketID, client);
            client->m_writeLogEvent = writeLog;
            client->m_recvEvent = recvServerMsg;
            m_clientsLock.unLock();
            return socketID;
        }
        else{
            delete client;
            client = 0;
            return -1;
        }
    }

    void FCClientSockets::registerLog(WriteClientLog writeLogCallBack){
        m_writeClientLogCallBack = writeLogCallBack;
    }

    void FCClientSockets::registerRecv(RecvMsg recvMsgCallBack){
        m_recvServerMsgCallBack = recvMsgCallBack;
    }

    int FCClientSockets::send(int socketID, const char *str, int len){
        return FCClientSocket::send(socketID, str, len);
    }
}
